/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.hauntedhouses.dao.impl;

import cz.muni.fi.hauntedhouses.dao.UsersDAO;
import cz.muni.fi.hauntedhouses.entity.Users;
import cz.muni.fi.hauntedhouses.to.UsersTO;
import cz.muni.fi.hauntedhouses.util.UserUtil;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Jan Volmut, 324836
 */
@Repository
public class UsersDAOImpl implements UsersDAO {
    
    private EntityManager em;
    
    @PersistenceContext
    public void setEntityManagerFactory(EntityManager em) {
        this.em = em;
    }
    
    @Override
    public void create(UsersTO user) {
        if(user == null) {
            throw new IllegalArgumentException("User is null");
        }
        
        Users user_dao = UserUtil.TOToEntity(user);

        this.em.persist(user_dao);
        user.setId(user_dao.getId());
    }

    @Override
    public UsersTO get(Long id) {
        if(id == null || id < 1) {
            throw new IllegalArgumentException("Id cannot be less than 1");
        }
        
        Users user = this.em.find(Users.class, id);
        UsersTO user_to = UserUtil.entityToTO(user);
        return user_to;
    }

    @Override
    public void update(UsersTO user) {
        if(user == null) {
            throw new IllegalArgumentException("House is null");
        }
        Users user_dao = UserUtil.TOToEntity(user);
        this.em.merge(user_dao);
    }

    @Override
    public void delete(UsersTO user) {
        if(user == null || user.getId() == null) {
            throw new IllegalArgumentException("House or id is null");
        }
        
        Users user_dao = UserUtil.TOToEntity(user);
        Users savedUser = this.em.getReference(Users.class, user_dao.getId());
        try {
        this.em.remove(savedUser);
        } catch(PersistenceException ex) {
            throw new IllegalArgumentException();
        }
    }
    
}